﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;

namespace Charities
{
    public partial class UsersMgmt : Form
    {
        int userId = -1;
        Form fo = null;
        public bool is_loaded = false;
        public UsersMgmt(int id,Form m)
        {
            fo = m;
            this.MdiParent = m;
            userId = id;
            InitializeComponent();
        }
        private static bool IsShown = false;
        public new void Show()
        {
            if (IsShown)
                base.Show();
            else
            {
                base.Show();
                IsShown = true;
            }
        }
        ModelContainer ctx = new ModelContainer();
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        bool grant_Modify = false;
        private void UsersMgmt_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userId);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Id)
                {
                    case 50:
                        btn_Add.Visible = true;
                        break;
                    case 51:
                        grant_Modify = true;
                        break;
                    case 52:
                        btn_delete.Visible = true;
                        break;
                    default:
                        break;
                }
            }
        }

        
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            AddNewUser a = new AddNewUser(this,fo);
            a.FormUpdated += new AddNewUser.UpdateFormHandler(btn_insert_Click);
            a.Show();
        }
        
        private void btn_insert_Click(object sender, UpdateFormEventArg e)
        {

            userBindingSource.DataSource = null;
            userBindingSource.DataSource = (from u in ctx.Users select u).ToList();
            dataGridView1.DataSource = userBindingSource;

        }
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int id=(int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
                User u = ctx.Users.Single(c => c.Id == id);
                u.username = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                u.password = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
                Role ro = ctx.Roles.Single(r => r.Id == id);
                u.RoleId = ro.Id;
                ctx.SaveChanges();

            }
            catch (Exception)
            {

                MessageBox.Show("connection error");  
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (grant_Modify)
            {
                int id = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
                AddNewUser a = new AddNewUser(id, this, fo);
                //  a.FormUpdated += new AddNewUser.UpdateFormHandler(btn_insert_Click);
                a.Show();
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    int id = (int)dataGridView1.Rows[i].Cells[0].Value;
                    User u=ctx.Users.Single(c=>c.Id==id);
                    if (ctx.Batches.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Entries.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Worthies.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.WorthyTypes.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.People.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Schedules.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Supplies.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.SupplyTypes.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Users.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0 ||
                        ctx.Roles.Where(c => c.InsertUId == id || c.UpdateUId == id).Count() > 0)
                    {
                        MessageBox.Show("لايمكن حذف المستخدم :"+u.username+" لكون المستخدم قد قام بعمل إضافة أو تعديل أو حذف في أحد الحقول ");

                    }
                    else
                    {
                        ctx.Users.Remove(u);
                        ctx.SaveChanges();
                        userBindingSource.DataSource = null;
                        userBindingSource.DataSource = ctx.Users.ToList();
                    }
                }
            }
            catch (Exception)
            {

                MessageBox.Show("خطأ لا يمكن الحذف");
            }
        }

        private void UsersMgmt_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void UsersMgmt_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
            dataGridView1.Rows.Clear();
            userBindingSource.DataSource = null; 
            userBindingSource.DataSource = ctx.Users.ToList(); 
            roleBindingSource.DataSource = null;
                
            roleBindingSource.DataSource = ctx.Roles.ToList();
           
        }

        private void dataGridView1_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("نقر مزدوج على الاسم لتغيير كلمة المرور ",this,2000);
        }
    }
}
